package com.star.oauth2.resource.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户信息API控制器
 * 
 * 提供当前登录用户的信息
 * 
 * @author star
 */
@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserController {

    /**
     * 获取当前用户信息
     * 从JWT令牌中解析用户信息
     */
    @GetMapping("/info")
    public Map<String, Object> getUserInfo(Authentication authentication) {
        Map<String, Object> userInfo = new HashMap<>();
        
        if (authentication != null && authentication.getPrincipal() instanceof Jwt jwt) {
            userInfo.put("username", jwt.getClaimAsString("sub"));
            userInfo.put("scopes", jwt.getClaimAsStringList("scope"));
            userInfo.put("issuedAt", jwt.getIssuedAt());
            userInfo.put("expiresAt", jwt.getExpiresAt());
            userInfo.put("issuer", jwt.getIssuer());
            
            log.info("获取用户信息: {}", jwt.getClaimAsString("sub"));
        } else {
            userInfo.put("error", "未找到认证信息");
        }
        
        return userInfo;
    }

    /**
     * 获取JWT原始信息（用于调试）
     */
    @GetMapping("/jwt")
    public Map<String, Object> getJwtInfo(Authentication authentication) {
        Map<String, Object> jwtInfo = new HashMap<>();
        
        if (authentication != null && authentication.getPrincipal() instanceof Jwt jwt) {
            jwtInfo.put("headers", jwt.getHeaders());
            jwtInfo.put("claims", jwt.getClaims());
            jwtInfo.put("tokenValue", jwt.getTokenValue().substring(0, 20) + "...");
            
            log.info("获取JWT信息");
        } else {
            jwtInfo.put("error", "未找到JWT信息");
        }
        
        return jwtInfo;
    }

}

